﻿//
// Copyright (c) 2011 HyperCrunch, Inc. http://www.hypercrunch.com 
// Author: Nik Kalyani  http://www.kalyani.com (Twitter: @techbubble)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using DotNetNuke.Entities.Modules;
using Telerik.Web.UI;
using System.Collections;
using System.Xml;
using System.IO;
using System.Xml.XPath;
using System.Collections.Generic;
using DotNetNuke.Services.Localization;
using System.Text;
using System.Web.UI;
using DotNetNuke.Security;

namespace HyperCrunch.Druid
{
    public partial class RuleEditor : PortalModuleBase
    {
        public string ConfigFile { get; set; }

        private string JsonHelpInfoText {

            get
            {
                StringBuilder jsonHelp = new StringBuilder();

                jsonHelp.Append(GetJsonHelp("RuleId"));
                jsonHelp.Append(GetJsonHelp("MatchType"));
                jsonHelp.Append(GetJsonHelp("MatchCustomType"));
                jsonHelp.Append(GetJsonHelp("MatchField"));
                jsonHelp.Append(GetJsonHelp("MatchValues"));
                jsonHelp.Append(GetJsonHelp("MatchCondition"));
                jsonHelp.Append(GetJsonHelp("IgnoreIf"));
                jsonHelp.Append(GetJsonHelp("AllowOverride"));
                jsonHelp.Append(GetJsonHelp("Order"));
                jsonHelp.Append(GetJsonHelp("ContinueAfterMatch"));
                jsonHelp.Append(GetJsonHelp("SkinSrc"));
                jsonHelp.Append(GetJsonHelp("ContainerSrc"));
                jsonHelp.Append(GetJsonHelp("ContentRenderer"));
                jsonHelp.Append(GetJsonHelp("ContentModifier"));
                jsonHelp.Append(GetJsonHelp("StylesheetUrl"));
                jsonHelp.Append(GetJsonHelp("ScriptUrl"));
                jsonHelp.Append(GetJsonHelp("RedirectUrl"));
                jsonHelp.Append(GetJsonHelp("JsonSettingName"));
                jsonHelp.Append(GetJsonHelp("JsonSettingValue"));
                return jsonHelp.ToString().Substring(1);
            }            
        }

        private string GetJsonHelp(string key)
        {
            return ",'" + key + "': '" + Localization.GetString("lbl" + key + ".HelpInfo", LocalResourceFile) + "'";
        }

        private string FilePath { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            ConfigFile = "";
            if (Request.IsAuthenticated)
            {
                if (UserInfo.IsSuperUser)
                    ConfigFile = "~/Portals/_default/druid.config";
                else
                    ConfigFile = ("~/" + PortalSettings.HomeDirectory.Substring(PortalSettings.HomeDirectory.IndexOf("/Portals")) + "/druid.config").Replace("//", "/");
                FilePath = Server.MapPath(ConfigFile);
                if (!File.Exists(FilePath))
                    File.WriteAllText(FilePath, "<Rules><Rule id=\"Example\" matchType=\"Request\" matchCondition=\"Equal\" matchField=\"example\" matchValues=\"none\" /></Rules>");
                JsonHelpInfo.Text = "<script type='text/javascript'>var helpInfo = {" + JsonHelpInfoText + "};</script>";
                RulesList.ExpandAllItems();
            }
            else
                RulesList.Visible = false;
        }

        protected void RulesList_NeedDataSource(object sender, TreeListNeedDataSourceEventArgs e)
        {
            RulesList.DataSource = GetRules();
        }

        private List<Rule> GetRules()
        {
            if (!Request.IsAuthenticated) return new List<Rule>();

            RuleCollection rules = RuleDefinition.GetRules(FilePath, UserInfo.IsSuperUser);
            List<Rule> rulesList = new List<Rule>();

            foreach (Rule rule in rules)
            {
                rulesList.Add(rule);
                rulesList.AddRange(GetChildRules(rule));
            }

            return rulesList;
        }

        private List<Rule> GetChildRules(Rule rule)
        {
            List<Rule> childRules = new List<Rule>();
            if (rule.Rules != null)
            {
                foreach (Rule childRule in rule.Rules)
                {
                    childRule.ParentId = rule.Id;
                    childRules.Add(childRule);
                    childRules.AddRange(GetChildRules(childRule));
                }
            }

            return childRules;
        }

        protected void RulesList_ItemCommand(object sender, TreeListCommandEventArgs e)
        {
            if (e.CommandName == "CustomItemsDropped")
            {
                TreeListDataItem item = e.Item as TreeListDataItem;
                Hashtable ht = new Hashtable();
                item.ExtractValues(ht);

                string sourceRuleId = ht["Id"].ToString();
                string targetRuleId = e.CommandArgument.ToString();

                RuleDefinition.MoveRule(FilePath, sourceRuleId, targetRuleId);
            }
            else if (e.CommandName == "MoveToRoot")
            {
                TreeListDataItem item = e.Item as TreeListDataItem;
                Hashtable ht = new Hashtable();
                item.ExtractValues(ht);

                string ruleId = ht["Id"].ToString();

                RuleDefinition.MoveRuleToRoot(FilePath, ruleId);
                Response.Redirect(Request.Url.AbsoluteUri);
            }
        }

        protected void RulesList_UpdateCommand(object source, TreeListCommandEventArgs e)
        {
            TreeListEditFormItem item = e.Item as TreeListEditFormItem;
            string ruleId = item.SavedOldValues["Id"].ToString();
            Hashtable ht = new Hashtable();
            item.ExtractValues(ht);

            RuleDefinition.UpdateRule(FilePath, ruleId, ht);
        }

        protected void RulesList_InsertCommand(object source, TreeListCommandEventArgs e)
        {
            TreeListEditFormInsertItem item = e.Item as TreeListEditFormInsertItem;

            string parentRuleId = "";
            if (item.ParentItem != null)
                parentRuleId = item.ParentItem.GetDataKeyValue("Id").ToString();

            Hashtable ht = new Hashtable();
            item.ExtractValues(ht);

            RuleDefinition.InsertRule(FilePath, parentRuleId, ht);
        }

        protected void RulesList_DeleteCommand(object source, TreeListCommandEventArgs e)
        {
            TreeListDataItem item = e.Item as TreeListDataItem;
            Hashtable ht = new Hashtable();
            item.ExtractValues(ht);
            string ruleId = ht["Id"].ToString();

            RuleDefinition.DeleteRule(FilePath, ruleId, ht);
        }


        private string ConvertNullToEmpty(Object obj)
        {
            return obj == null ? String.Empty : obj.ToString();
        }

        protected override void Render(HtmlTextWriter writer)
        {
            Page.ClientScript.RegisterForEventValidation(RulesList.UniqueID);
            base.Render(writer);
        }

    }
}